package com.demo.studentmanager.shiro;

import com.demo.studentmanager.entity.Role;
import com.demo.studentmanager.entity.User;
import com.demo.studentmanager.service.IRoleService;
import com.demo.studentmanager.service.IUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

/**
 * 自定义Realm
 *
 * @author wx
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private IUserService userService;

    @Autowired
    private IRoleService roleService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        User user = (User) principalCollection.getPrimaryPrincipal();

        Set<String> roles = new HashSet<>();
        Set<String> permissions = new HashSet<>();

        Role role = roleService.getById(user.getRoleId());
        roles.add(role.getRoleName());

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(roles);
        info.setStringPermissions(permissions);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

//        编写shiro判断逻辑，判断用户名和密码
        User user = userService.getById(token.getUsername());
//        1.判断用户名
        if (user == null) {
//            用户名不存在
            return null;
        }

//        2.判断密码
        return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
    }
}
